package org.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.TimeUnit;

/**
 * Curator客户端工具类
 */
public class CuratorClientUtils {

    // 集群连接地址
    private final static  String CONNECTSTRING =
            "10.10.10.91:2181,10.10.10.92:2181,10.10.10.93:2181";

    private static CuratorFramework curatorFramework;

    public static CuratorFramework getInstance(){
        curatorFramework = CuratorFrameworkFactory.newClient(
                CONNECTSTRING,5000,5000,new ExponentialBackoffRetry(1000,3));
        curatorFramework.start();
        return curatorFramework;
    }




 //创建节点
    public static void  create() throws  Exception{

        System.err.println(getInstance());
        // 创建节点
        String s = getInstance().create()
                // 同时创建父节点与子节点
                .creatingParentContainersIfNeeded()
                // PERSISTENT 永久节点  EPHEMERAL 临时节点
                .withMode(CreateMode.PERSISTENT)
                .forPath("/cch1/xjx1", "123".getBytes());
        System.out.println(s);
    }
    //修改节点
    public static void  update() throws  Exception{

        // 修改数据
        Stat stat1 = getInstance().setData().forPath("/cch/xjx", "99".getBytes());
        System.out.println(stat1);

        // 查询/获取数据
        Stat stat2 = new Stat();
        byte[] bytes2 = curatorFramework.getData().storingStatIn(stat2).forPath("/curator");
        System.out.println(new String(bytes2) + " ---> stat: " + stat2);
    }

    //修改节点
    public static void  delete() throws  Exception{

        // 删除节点
        getInstance().delete()
                // 同时删除父节点与子节点
                .deletingChildrenIfNeeded()
                .forPath("/cch/xjx");
        System.out.println("删除成功...........");
    }



//节点的监听
    public static void main(String[] args) throws Exception {
      create();
    }




}